package cn.xscrum.vtsp.controller;

import cn.xscrum.common.annotation.Log;
import cn.xscrum.common.core.controller.BaseController;
import cn.xscrum.common.core.domain.AjaxResult;
import cn.xscrum.common.core.page.TableDataInfo;
import cn.xscrum.common.core.text.Convert;
import cn.xscrum.common.enums.BusinessType;
import cn.xscrum.common.utils.poi.ExcelUtil;
import cn.xscrum.vtsp.domain.*;
import cn.xscrum.vtsp.service.*;
import com.alibaba.fastjson.JSON;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 志愿者管理Controller
 *
 * @author liuwl
 * @date 2021-10-01
 */
@Controller
@RequestMapping("/vtsp/volunteermanage")
public class VtspVolunteerManageController extends BaseController
{
    //template资源前缀
    private String prefix = "vtsp/volunteermanage";

    @Autowired
    private IVtspVolunteerManageService vtspVolunteerManageService; //定义志愿者管理Service接口对象

    @Autowired
    private IVtspAreasService vtspAreasService; //定义国家地区管理Service接口对象

    @Autowired
    private IVtspSectorService vtspSectorService;   //定义部门Service接口对象

    @Autowired
    private IVtspDutiesService vtspDutiesService;   //定义职务Service接口对象

    @Autowired
    private IVtspAcademyService vtspAcademyService; //定义学院Service接口对象

    @Autowired
    private IVtspEnrollService vtspEnrollService; //定义报名Service接口对象

    @Autowired
    private IVtspAppraiseService vtspAppraiseService; //定义评价Service接口对象

    /**
     * 初始加载的志愿者信息
     *
     * @return 志愿者管理页面
     */
    @RequiresPermissions("team:volunteermanage:view")
    @GetMapping()
    public String volunteer(Model model)
    {
        //获取部门列表
        List<VtspSector> sectorList = vtspSectorService.selectVtspSectorList(new VtspSector());
        //获取学院列表
        List<VtspAcademy> academyList = vtspAcademyService.selectVtspAcademyList(new VtspAcademy());
        model.addAttribute("sectorList", sectorList);
        model.addAttribute("academyList", academyList);
        return prefix + "/volunteermanage";
    }

    /**
     * 查询志愿者列表
     *
     * @param vtspVolunteerManage 志愿者信息
     * @return 查询到的志愿者信息列表
     */
    @RequiresPermissions("team:volunteermanage:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(VtspVolunteerManage vtspVolunteerManage)
    {
        //获取志愿者列表信息
        List<VtspVolunteerManage> list = vtspVolunteerManageService.selectVtspVolunteerManageList(vtspVolunteerManage);
        //数据回显
        for(VtspVolunteerManage volunteerManage : list)
        {
            if(volunteerManage != null)
            {
                String sector = volunteerManage.getSectorName();    //部门
                String duties = volunteerManage.getDutiesName();    //职务
                String academy = volunteerManage.getVolunteerAcademy();     //学院
                //利用正则表达式判断是否为数字
                Pattern pattern = Pattern.compile("[0-9]+");
                if((pattern.matcher(sector)).matches())        //部门为数字
                {
                    Long sectorId = Long.parseLong(sector);         //String转Long
                    VtspSector vtspSector = vtspSectorService.selectVtspSectorById(sectorId);
                    String sectorName = vtspSector.getSectorName();
                    volunteerManage.setSectorName(sectorName);        //回显
                }
                if((pattern.matcher(duties)).matches())        //职务为数字
                {
                    Long dutiesId = Long.parseLong(duties);         //String转Long
                    VtspDuties vtspDuties = vtspDutiesService.selectVtspDutiesById(dutiesId);
                    String dutiesName = vtspDuties.getDutiesName();
                    volunteerManage.setDutiesName(dutiesName);        //回显
                }
                if((pattern.matcher(academy)).matches())        //学院为数字
                {
                    Long academyId = Long.parseLong(academy);         //String转Long
                    VtspAcademy vtspAcademy = vtspAcademyService.selectVtspAcademyById(academyId);
                    String academyName = vtspAcademy.getAcademyName();
                    volunteerManage.setVolunteerAcademy(academyName);        //回显
                }
            }
        }
        startPage();
        return getDataTable(list);
    }

    /**
     * 新增志愿者管理
     *
     * @return 志愿者管理新增页面
     */
    @GetMapping("/add")
    public String add(Model model)
    {
        //获取部门列表
        List<VtspSector> sectorList = vtspSectorService.selectVtspSectorList(new VtspSector());
        //获取职务列表
        List<VtspDuties> dutiesList = vtspDutiesService.selectVtspDutiesList(new VtspDuties());
        //获取国家地区管理的数据
        List<VtspAreas> areasList = vtspAreasService.selectVtspAreasList(new VtspAreas());
        //获取学院列表
        List<VtspAcademy> academyList = vtspAcademyService.selectVtspAcademyList(new VtspAcademy());
        //获取vtsp_areas的国家信息，即parent_id = 0；若parent_id != 0，则为城市信息
        List<VtspAreas> countryList = new ArrayList<VtspAreas>();        //国家
        List<VtspAreas> cityList = new ArrayList<VtspAreas>();           //省市
        for(VtspAreas vtspAreas : areasList)
        {
            if(vtspAreas != null)
            {
                if(vtspAreas.getParentId() == 0)    //国家
                {
                    countryList.add(vtspAreas);
                }
                else
                {
                    cityList.add(vtspAreas);
                }
            }
        }
        model.addAttribute("countryList", countryList);
        model.addAttribute("cityList", JSON.toJSONString(cityList));
        model.addAttribute("sectorList", sectorList);
        model.addAttribute("dutiesList", dutiesList);
        model.addAttribute("academyList", academyList);
        return prefix + "/add";
    }

    /**
     * 新增保存志愿者管理
     *
     * @param vtspVolunteerManage 志愿者信息
     * @return 新增结果
     */
    @RequiresPermissions("team:volunteermanage:add")
    @Log(title = "志愿者管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(VtspVolunteerManage vtspVolunteerManage)
    {
        return toAjax(vtspVolunteerManageService.insertVtspVolunteerManage(vtspVolunteerManage));
    }

    /**
     * 修改志愿者信息
     *
     * @param volunteerId 志愿者信息ID
     * @param mmap ModelMap对象
     * @return 修改页面的数据
     */
    @GetMapping("/edit/{volunteerId}")
    public String edit(@PathVariable("volunteerId") Long volunteerId, ModelMap mmap)
    {
        //根据volunteerId查询需要修改的志愿者信息
        VtspVolunteerManage vtspVolunteerManage = vtspVolunteerManageService.selectVtspVolunteerManageById(volunteerId);
        //获取部门列表
        List<VtspSector> sectorList = vtspSectorService.selectVtspSectorList(new VtspSector());
        //获取职务列表
        List<VtspDuties> dutiesList = vtspDutiesService.selectVtspDutiesList(new VtspDuties());
        //获取国家地区管理的数据
        List<VtspAreas> areasList = vtspAreasService.selectVtspAreasList(new VtspAreas());
        //获取学院列表
        List<VtspAcademy> academyList = vtspAcademyService.selectVtspAcademyList(new VtspAcademy());
        //获取vtsp_areas的国家信息，即parent_id = 0；若parent_id != 0，则为城市信息
        List<VtspAreas> countryList = new ArrayList<VtspAreas>();        //国家
        List<VtspAreas> cityList = new ArrayList<VtspAreas>();           //省市
        for(VtspAreas vtspAreas : areasList)
        {
            if(vtspAreas != null)
            {
                if(vtspAreas.getParentId() == 0)    //国家
                {
                    countryList.add(vtspAreas);
                }
                else
                {
                    cityList.add(vtspAreas);
                }
            }
        }
        //获取adviserId的volunteer_areaid，由此获取vtsp_areas信息
        Long areasId = vtspVolunteerManage.getVolunteerAreaid();
        VtspAreas vtspAreas = vtspAreasService.selectVtspAreasById(areasId);
        //展示修改页面的数据
        mmap.put("vtspVolunteerManage", vtspVolunteerManage);
        mmap.put("countryList", countryList);
        mmap.put("cityList", JSON.toJSONString(cityList));
        mmap.put("vtspAreas",JSON.toJSONString(vtspAreas));
        mmap.put("sectorList", sectorList);
        mmap.put("dutiesList", dutiesList);
        mmap.put("academyList", academyList);
        return prefix + "/edit";
    }

    /**
     * 修改保存志愿者管理
     *
     * @param vtspVolunteerManage 志愿者信息
     * @return 修改结果
     */
    @RequiresPermissions("team:volunteermanage:edit")
    @Log(title = "志愿者管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(VtspVolunteerManage vtspVolunteerManage)
    {
        return toAjax(vtspVolunteerManageService.updateVtspVolunteerManage(vtspVolunteerManage));
    }

    /**
     * 批量删除志愿者信息
     *
     * @param ids 需要删除的数据ID
     * @return 批量删除结果
     */
    @RequiresPermissions("team:volunteermanage:remove")
    @Log(title = "志愿者管理", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        //先删除关联的志愿者评价信息和报名信息外键
        for(String id : Convert.toStrArray(ids))
        {
            Long volunteerId = Long.parseLong(id);      //志愿者Id
            //获取志愿者服务记录并删除
            List<VtspVolunteerManage> appraiseList = vtspVolunteerManageService.selectServeList(volunteerId);
            for(VtspVolunteerManage vtspVolunteerManage : appraiseList)
            {
                Long appraiseId = vtspVolunteerManage.getAppraiseId();
                vtspAppraiseService.deleteVtspAppraiseById(appraiseId);
            }
            //获取志愿者报名记录并删除
            List<VtspVolunteerManage> enrollList = vtspVolunteerManageService.selectEnrollList(volunteerId);
            for(VtspVolunteerManage vtspVolunteerManage : enrollList)
            {
                Long enrollId = vtspVolunteerManage.getEnrollId();
                vtspEnrollService.deleteVtspEnrollById(enrollId);
            }
        }
        return toAjax(vtspVolunteerManageService.deleteVtspVolunteerManageByIds(ids));
    }

    /**
     * 导入下载模板
     *
     * @return 模版
     */
    @RequiresPermissions("team:volunteermanage:view")
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate()
    {
        //创建Excel工具类
        ExcelUtil<VtspVolunteerManage> util = new ExcelUtil<VtspVolunteerManage>(VtspVolunteerManage.class);
        return util.importTemplateExcel("志愿者信息");
    }

    /**
     * 导入志愿者管理列表
     *
     * @param file 获取文件对象
     * @param updateSupport 是否更新支持，如果已存在，则进行更新数据
     * @return 导入成功结果
     */
    @RequiresPermissions("team:volunteermanage:import")
    @Log(title = "志愿者管理", businessType = BusinessType.IMPORT)
    @PostMapping("/import")
    @ResponseBody
    public AjaxResult importList(MultipartFile file, Boolean updateSupport) throws Exception
    {
        //创建Excel工具类
        ExcelUtil<VtspVolunteerManage> util = new ExcelUtil<VtspVolunteerManage>(VtspVolunteerManage.class);
        //选择导入文件
        List<VtspVolunteerManage> list = util.importExcel(file.getInputStream());
        //导入文件
        String message = vtspVolunteerManageService.importList(list, updateSupport);
        return AjaxResult.success(message);
    }

    /**
     * 导出志愿者管理列表
     *
     * @param vtspVolunteerManage 志愿者信息
     * @return 结果
     */
    @RequiresPermissions("team:volunteermanage:export")
    @Log(title = "志愿者管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult exportList(VtspVolunteerManage vtspVolunteerManage)
    {
        //获取志愿者信息
        List<VtspVolunteerManage> list = vtspVolunteerManageService.selectVtspVolunteerManageList(vtspVolunteerManage);
        //创建Excel表格并导出
        ExcelUtil<VtspVolunteerManage> util = new ExcelUtil<VtspVolunteerManage>(VtspVolunteerManage.class);
        return util.exportExcel(list, "volunteerManage");
    }

    /**
     * 查看志愿者详情
     *
     * @param volunteerId 志愿者信息ID
     * @param mmap ModelMap对象
     * @return 志愿者详情列表
     */
    @GetMapping("/detail/{volunteerId}")
    public String detail(@PathVariable("volunteerId") Long volunteerId, ModelMap mmap)
    {
        //根据volunteerId查询志愿者信息
        VtspVolunteerManage vtspVolunteerManage = vtspVolunteerManageService.selectVtspVolunteerManageById(volunteerId);
        if(vtspVolunteerManage != null)
        {
            String sector = vtspVolunteerManage.getSectorName();    //部门
            String duties = vtspVolunteerManage.getDutiesName();    //职务
            String academy = vtspVolunteerManage.getVolunteerAcademy();     //学院
            //利用正则表达式判断duties是否为数字
            Pattern pattern = Pattern.compile("[0-9]+");
            if((pattern.matcher(sector)).matches())        //部门为数字
            {
                Long sectorId = Long.parseLong(sector);         //String转Long
                VtspSector vtspSector = vtspSectorService.selectVtspSectorById(sectorId);
                String sectorName = vtspSector.getSectorName();
                vtspVolunteerManage.setSectorName(sectorName);        //回显
            }
            if((pattern.matcher(duties)).matches())        //职务为数字
            {
                Long dutiesId = Long.parseLong(duties);         //String转Long
                VtspDuties vtspDuties = vtspDutiesService.selectVtspDutiesById(dutiesId);
                String dutiesName = vtspDuties.getDutiesName();
                vtspVolunteerManage.setDutiesName(dutiesName);        //回显
            }
            if((pattern.matcher(academy)).matches())        //学院为数字
            {
                Long academyId = Long.parseLong(academy);         //String转Long
                VtspAcademy vtspAcademy = vtspAcademyService.selectVtspAcademyById(academyId);
                String academyName = vtspAcademy.getAcademyName();
                vtspVolunteerManage.setVolunteerAcademy(academyName);        //回显
            }
        }
        //展示详情页面的数据
        mmap.put("vtspVolunteerManage", vtspVolunteerManage);
        return prefix + "/detail";
    }

    /**
     * 查询志愿者服务记录详情
     *
     * @param volunteerId 志愿者信息ID
     * @param mmap ModelMap对象
     * @return 查询到的志愿者服务记录
     */
    @PostMapping("/detail/{volunteerId}/serve")
    @ResponseBody
    public TableDataInfo listA(@PathVariable("volunteerId") Long volunteerId, ModelMap mmap)
    {
        mmap.put("volunteerId" ,volunteerId);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  //日期格式化
        //获取志愿者服务记录
        List<VtspVolunteerManage> list = vtspVolunteerManageService.selectServeList(volunteerId);
        for(VtspVolunteerManage vtspVolunteerManage : list)
        {
            if(vtspVolunteerManage != null)
            {
                //设置活动时间为：活动开始时间 至 活动结束时间
                String activityTime = sdf.format(vtspVolunteerManage.getActivityBegin()) + " 至 " + sdf.format(vtspVolunteerManage.getActivityEnd());
                vtspVolunteerManage.setActivityTime(activityTime);
            }
        }
        startPage();
        return getDataTable(list);
    }

    /**
     * 查询志愿者报名记录详情
     *
     * @param volunteerId 志愿者信息ID
     * @param mmap ModelMap对象
     * @return 查询到的志愿者报名记录
     */
    @PostMapping("/detail/{volunteerId}/enroll")
    @ResponseBody
    public TableDataInfo listB(@PathVariable("volunteerId") Long volunteerId, ModelMap mmap)
    {
        mmap.put("volunteerId" ,volunteerId);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  //日期格式化
        //获取志愿者报名记录
        List<VtspVolunteerManage> list = vtspVolunteerManageService.selectEnrollList(volunteerId);
        for(VtspVolunteerManage vtspVolunteerManage : list)
        {
            if(vtspVolunteerManage != null)
            {
                //设置活动时间为：活动开始时间 至 活动结束时间
                String activityTime = sdf.format(vtspVolunteerManage.getActivityBegin()) + " 至 " + sdf.format(vtspVolunteerManage.getActivityEnd());
                vtspVolunteerManage.setActivityTime(activityTime);
            }
        }
        startPage();
        return getDataTable(list);
    }

    /**
     * 移入黑名单 修改志愿者状态为黑名单志愿者9
     *
     * @param volunteerId 志愿者信息ID
     * @return 结果
     */
    @RequiresPermissions("team:volunteermanage:blacklist")
    @Log(title = "志愿者管理", businessType = BusinessType.UPDATE)
    @PostMapping( "/blacklist")
    @ResponseBody
    public AjaxResult toBlacklist(Long volunteerId)
    {
        return toAjax(vtspVolunteerManageService.moveVtspVolunteerManageById(volunteerId));
    }
}
